<?php
/*
 * 比较2个值，计算百分比返回.
 */
if (!function_exists('compareValue')) {
    function compareValue($new, $old)
    {
        if ($new == $old) {
            return '0';
        }
        if ($new > 0 && $old == 0) {
            return '+1';
        }
        if ($new == 0 && $old > 0) {
            return '-1';
        }
        if ($new > 0 && $old > 0) {
            $campare = ($new - $old) / $old;

            return sprintf('%.1f', $campare);
        }
    }
}
/*
 * 检测一个远程文件是否存在
 */
if (!function_exists('my_file_exists')) {
    function my_file_exists($file)
    {
        if (preg_match('|^https://|', $file)) {
            //如果是远程文件
            $ch = curl_init($file);
            curl_setopt($ch, CURLOPT_HEADER, 1); //输出文件头信息
            curl_setopt($ch, CURLOPT_NOBODY, 1); //不输出文件主体
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //将curl_exec()返回到变量
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //设置超时
            $contents = curl_exec($ch); //获取远程文件信息

            return preg_match('|HTTP/1.1 200|', $contents) ? true : false; //如果状态不是200,就表示获取失败。
        }

        return file_exists($file);
    }
}
/*
 * 生成一个token.
 */
if (!function_exists('getToken')) {
    function getToken($token = null)
    {
        if ($token) {
            return md5(time() . $token);
        } else {
            return md5(time());
        }
    }
}
/*
 * 生成订单号.
 * 订单号3位字母+10个数字组合
 */
if (!function_exists('get_microtimes')) {
    function get_microtimes($prefix = 'BAP')
    {
        list($usec, $sec) = explode(' ', microtime());

        return $prefix . date('md', time()) . substr($usec, 2, 2) . rand(1000, 9999);
    }
}

/*
 * 生成一个账号account.
 */
if (!function_exists('getAccount')) {
    function getAccount()
    {
        return 'BAP_' . date('md', time()) . getCode(2, 2) . rand(1111, 9999);
    }
}
/*
 * 生成一个昵称.
 */
if (!function_exists('getNickname')) {
    function getNickname()
    {
        return '会员' . getCode(4, 3) . '_' . rand(111111111, 999999999);
    }
}
/*
 * 生成一个用户标识符.
 */
if (!function_exists('getSign')) {
    function getSign()
    {
        return substr(md5(time() . getCode(3, 10)), 12, 12);
    }
}
/*
 * 判定是否手机号.
 */
if (!function_exists('isPhone')) {
    function isPhone($phone)
    {
        if (preg_match("/^1[345789]{1}\d{9}$/", $phone)) {
            return true;
        } else {
            return false;
        }
    }
}
/*
 * 判定是否邮箱
 */
if (!function_exists('isEmail')) {
    function isEmail($email)
    {
        if (preg_match('/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i', $email)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('isIdentity')) {
    function isIdentity($identity)
    {
        if (preg_match("/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/", $identity)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('isPosition')) {
    function isPosition($position)
    {
        if (preg_match("/^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$/", $position)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('isPassword')) {
    function isPassword($position)
    {
        if (preg_match('/^[a-zA-Z0-9]{6,10}$/', $position)) {
            return true;
        } else {
            return false;
        }
    }
}

/*
 * 生成一个随机字符串.
 */
function getCode($type = 1, $length = 6)
{
    switch ($type) {
        case 1: //数字
            $str = str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_BOTH);
            break;
        case 2: //字母
            $arr = range('a', 'z');
            shuffle($arr);
            $str = str_shuffle(substr(implode('', $arr), 0, $length));
            break;
        case 3: //数字字母混合
            $string = range('a', 'z');
            $number = range(0, 9);
            $array  = array_merge($string, $number);
            shuffle($array);
            $str = str_shuffle(substr(implode('', $array), 0, $length));
            break;
        case 4: //大写字母
            $arrS = range('A', 'Z');
            shuffle($arrS);
            $str = str_shuffle(substr(implode('', $arrS), 0, $length));
            break;
    }

    return $str;
}

/*
 * 根据短信类型返回短信模板
 */
if (!function_exists('getTemplate')) {
    function getTemplate($type)
    {
        switch ($type) {
            case 1: //登陆验证
                $template = '172825';
                break;
            case 2: //注册验证
                $template = '172823';
                break;
            case 3: //忘记密码
                $template = '172823';
                break;
            case 4: //修改密码
                $template = '172823';
                break;
            default:
                $template = '172822';
                break;
        }

        return $template;
    }
}

/*
 * 传入时间戳数组，转为日期格式，并过滤掉重复值
 */
if (!function_exists('filter_repeat_date')) {
    function filter_repeat_date(array $times)
    {
        $arr = [];
        foreach ($times as $key => $time) {
            $arr[$key] = date('Y-m-d', $time);
        }
        $arr = array_flip(array_flip($arr));

        return $arr;
    }
}
/*
 * 列出2个日期之间的所有日期
 *
 * @param 时间戳
 */
if (!function_exists('get_date_list')) {
    function get_date_list($start, $end)
    {
        $dt_start = $start;
        $dt_end   = $end;
        $arr      = [];
        while ($dt_start <= $dt_end) {
            $arr[]    = date('Y-m-d', $dt_start);
            $dt_start = strtotime('+1 day', $dt_start);
        }

        return $arr;
    }
}
/*
 * 模拟post请求
 *
 * @param $url 请求地址
 * @param $param 请求参数
 */
if (!function_exists('request_post')) {
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl  = $url;
        $curlPost = $param;
        $ch       = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);

        return $data;
    }
}

/*
 *   加密密码
 */
if (!function_exists('md5Password')) {
    function md5Password($password, $uid)
    {
        return md5($password . $uid . config('event.password_key'));
    }
}

/*
 *   随机选择一张头像图片
 */
if (!function_exists('randomHeadimg')) {
    function randomHeadimg()
    {
        return '/bap/headimg/' . rand(1, 3) . '.png';
    }
}

/**
 * $array 要排序的数组
 * $field  排序依据列
 * $sort 排序类型[asc or desc]
 * return 排好序的数组.
 */
function arraySort($array, $field, $sort = 'SORT_DESC')
{
    $arrSort = array();
    foreach ($array as $uniqid => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }
    array_multisort($arrSort[$field], constant($sort), $array);

    return $array;
}

/*
 * 过滤url地址？后面的参数
 */
if (!function_exists('cut_url')) {
    function cut_url($url)
    {
        $arr = explode('?', $url);

        return $arr[0];
    }
}

/*
 *  获取交易行情（比特币交易网）
 *  参数支持：btc,eth,etc,ltc,doge,ybc
 */
if (!function_exists('getBtctradeTicker')) {
    function getBtctradeTicker($currency)
    {
        if (!in_array(strtolower($currency), ['btc', 'eth', 'etc', 'ltc', 'doge', 'ybc'])) {
            return false;
        }
        $url  = 'https://api.btctrade.com/api/ticker?coin=' . strtolower($currency);
        $data = file_get_contents($url);

        return json_decode($data)->last;
    }
}

/*
 *  Okcoin交易行情（兑换CNY）
 *  参数支持:btc_cny,ltc_cny,eth_cny,etc_cny,bch_cny
 */
if (!function_exists('getOkCoinTicker')) {
    function getOkCoinTicker($currency)
    {
        if (!in_array(strtolower($currency), ['btc_cny', 'ltc_cny', 'eth_cny', 'etc_cny', 'bch_cny'])) {
            return false;
        }
        $url  = 'https://www.okcoin.cn/api/v1/ticker.do?symbol=' . strtolower($currency);
        $data = file_get_contents($url);

        return json_decode($data)->ticker->last;
    }
}

/*
 * 格式化价格
 */
if (!function_exists('price_format')) {
    function price_format($price, $num = 2)
    {
        return number_format($price, $num, '.', '');
    }
}

if (!function_exists('reckonIndex')) {
    function reckonIndex($cid, $type)
    {
        return $cid . '000' . $type;
    }
}
/*
 * 接口错误返回
 */
if (!function_exists('respF')) {
    function respF($error_code)
    {
        //判断错误号是否存在
        if (!array_key_exists($error_code, config('error_code'))) {
            //未找到给默认提示
            $error_code = '9999';
        }
        //获取配置
        $conf = config('error_code')[$error_code];
        //提示消息
        $msg = $conf['msg'];
        //如果不展示，消息内容为错误号
        if ($conf['show'] == 0) {
            $msg = $error_code;
        }
        //返回
        if ($conf['show'] == -1) {
            return response()->json([
                'status'     => -1,
                'error_code' => $error_code,
                'msg'        => $msg,
            ]);
        }

        return response()->json([
            'status'     => 0,
            'error_code' => $error_code,
            'msg'        => $msg,
        ]);
    }
}

/*
 * 格式化数字(不四舍五入)
 */
if (!function_exists('NumberFormat')) {
    function NumberFormat($number, $n = 4)
    {
        $numStr = (string) $number . str_repeat('0', $n);

        //匹配精度前的数值
        if (preg_match('#^\d+\.\d{0,' . $n . '}#', $numStr, $match)) {
            return $match[0];
        } else {
            return '0';
        }
    }
}

function GetIp()
{
    $realip  = '';
    $unknown = 'unknown';
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])
            && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr as $ip) {
                $ip = trim($ip);
                if ($ip != 'unknown') {
                    $realip = $ip;
                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])
            && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR'])
            && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
            $realip = $_SERVER['REMOTE_ADDR'];
        } else {
            $realip = $unknown;
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)) {
            $realip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)) {
            $realip = getenv('REMOTE_ADDR');
        } else {
            $realip = $unknown;
        }
    }
    $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;

    return $realip;
}

function GetIpLookup($ip = '')
{
    if (empty($ip)) {
        $ip = GetIp();
    }
    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    if (empty($res)) {
        return false;
    }
    $jsonMatches = array();
    preg_match('#\{.+?\}#', $res, $jsonMatches);
    if (!isset($jsonMatches[0])) {
        return false;
    }
    $json = json_decode($jsonMatches[0], true);
    if (isset($json['ret']) && $json['ret'] == 1) {
        $json['ip'] = $ip;
        unset($json['ret']);
    } else {
        return false;
    }

    return $json;
}

function splitName($fullname)
{
    $hyphenated = array('欧阳', '太史', '端木', '上官', '司马', '东方', '独孤', '南宫', '万俟', '闻人', '夏侯', '诸葛', '尉迟', '公羊', '赫连', '澹台', '皇甫',
        '宗政', '濮阳', '公冶', '太叔', '申屠', '公孙', '慕容', '仲孙', '钟离', '长孙', '宇文', '城池', '司徒', '鲜于', '司空', '汝嫣', '闾丘', '子车', '亓官',
        '司寇', '巫马', '公西', '颛孙', '壤驷', '公良', '漆雕', '乐正', '宰父', '谷梁', '拓跋', '夹谷', '轩辕', '令狐', '段干', '百里', '呼延', '东郭', '南门',
        '羊舌', '微生', '公户', '公玉', '公仪', '梁丘', '公仲', '公上', '公门', '公山', '公坚', '左丘', '公伯', '西门', '公祖', '第五', '公乘', '贯丘', '公皙',
        '南荣', '东里', '东宫', '仲长', '子书', '子桑', '即墨', '达奚', '褚师');
    $vLength   = mb_strlen($fullname, 'utf-8');
    $lastname  = '';
    $firstname = ''; //前为姓,后为名
    if ($vLength > 2) {
        $preTwoWords = mb_substr($fullname, 0, 2, 'utf-8'); //取命名的前两个字,看是否在复姓库中
        if (in_array($preTwoWords, $hyphenated)) {
            $lastname  = $preTwoWords;
            $firstname = mb_substr($fullname, 2, 10, 'utf-8');
        } else {
            $lastname  = mb_substr($fullname, 0, 1, 'utf-8');
            $firstname = mb_substr($fullname, 1, 10, 'utf-8');
        }
    } elseif ($vLength == 2) {
        //全名只有两个字时,以前一个为姓,后一下为名
        $lastname  = mb_substr($fullname, 0, 1, 'utf-8');
        $firstname = mb_substr($fullname, 1, 10, 'utf-8');
    } else {
        $lastname = $fullname;
    }

    return array($lastname, $firstname);
}

/*
 * 获取美元兑人民币汇率
 */
if (!function_exists('UsdRate')) {
    function UsdRate()
    {
        $data = file_get_contents('http://www.baidu.com/s?wd=USD%20CNY&rsv_spt=1');

        preg_match("/<div>1\D*=(\d*\.\d*)\D*<\/div>/", $data, $converted);

        if (empty($converted)) {
            return 6.3;
        }

        $converted = preg_replace('/[^0-9.]/', '', $converted[1]);

        return number_format(round($converted, 3), 2);
    }
}
//用户名、邮箱、手机账号开头字符串以*隐藏
if (!function_exists('hideStar')) {
    function hideStar($str)
    {
        if (strpos($str, '@')) {
            $email_array = explode("@", $str);
            /*$prevfix = (strlen($email_array[0]) < 4) ? "" : substr($str, 0, 3); //邮箱前缀
            $count = 0;
            $str = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $str, -1, $count);
            $rs = $prevfix . $str;*/
            $prevfix = "****" . substr($email_array[0], -4);
            $rs      = $prevfix . '@' . $email_array[1];
        } else {
            $pattern = '/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i';
            if (preg_match($pattern, $str)) {
                $rs = preg_replace($pattern, '****$2', $str); // substr_replace($name,'****',3,4);
            } else {
                $rs = substr($str, 0, 3) . "***" . substr($str, -4);
            }
        }
        return $rs;
    }
}

//根据申述类型值返回申述类型说明
if (!function_exists('appealType')) {
    function appealType($type)
    {
        switch ($type) {
            case 1:
                return '对方未放币';
                break;
            case 2:
                return '对方无应答';
                break;
            case 3:
                return '对方未付款';
                break;
            case 4:
                return '对方有欺诈行为';
                break;
            case 5:
                return '其他';
                break;
            default:
                return '其他';
                break;
        }
    }
}

if (!function_exists('HandleShowStatus')) {
    /**
     * 处理订单显示状态
     * @param type 1 买入 2 卖出
     * @param status 订单状态 状态 1 未付款 2 已付款 3 已完成 4 已取消 5 申诉中 6 申述完结
     * @param num 查询源 1订单列表 2订单详情
     */
    function HandleShowStatus($type, $status, $num = 1)
    {
        //如果订单已取消，返回false
        if ($status == 4) {
            return 7;
        }

        //申述中，申述完结，返回申述中
        if (in_array($status, [5, 6])) {
            return 4;
        }

        //订单已付款
        if ($status == 2) {
            if ($type == 1) //买入返回待收币
            {
                return 2;
            }

            return 3; //卖出返回待发币
        }
        //订单已完成，返回已完成
        if ($status == 3) {
            return 5;
        }

        //如果源是详情
        if ($num == 2) {
            if ($type == 1) //买入返回未付款
            {
                return 1;
            }

            return 6; //卖出返回 待对方付款60分钟
        }

        //如果源是列表 返回未付款
        return 1;
    }
}


if (!function_exists('GetWhereGenre')) {

    /**
     * 组装订单查询条件
     * @param [type]  $genra 显示状态
     * @param [type]  $uid   用户ID
     * @param integer $type  分类 1是用户 2是商家
     */
    function GetWhereGenre($genre = null, $uid, $type = 1)
    {
        if ($genre == 1) {
            $where['status'] = 1;
        } elseif ($genre == 2) {
            $where['status'] = 2;
            $where['type']   = 1;
        } elseif ($genre == 3) {
            $where['status'] = 2;
            $where['type']   = 2;
        }
        if ($type == 1) {
            $where['uid'] = $uid;
        } else {
            $where['bid'] = $uid;
        }

        return $where;
    }
}
